package com.rbac.admin.config;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

/**
 * 初始化数据字典所需的表（仅在不存在时创建），避免首次访问报表不存在错误。
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DictionarySchemaInitializer {

    private final JdbcTemplate jdbcTemplate;

    @PostConstruct
    public void init() {
        try {
            // 创建表：表级配置
            jdbcTemplate.execute(
                    "CREATE TABLE IF NOT EXISTS sys_dict_table (" +
                            "id BIGINT PRIMARY KEY AUTO_INCREMENT, " +
                            "table_name VARCHAR(64) NOT NULL UNIQUE COMMENT '表名', " +
                            "table_comment VARCHAR(200) DEFAULT NULL COMMENT '表注释', " +
                            "enabled TINYINT DEFAULT 1 COMMENT '是否启用', " +
                            "remark VARCHAR(255) DEFAULT NULL, " +
                            "create_time DATETIME DEFAULT CURRENT_TIMESTAMP, " +
                            "update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP" +
                            ") COMMENT='数据字典-表级配置'"
            );

            // 创建表：字段级配置
            jdbcTemplate.execute(
                    "CREATE TABLE IF NOT EXISTS sys_dict_field (" +
                            "id BIGINT PRIMARY KEY AUTO_INCREMENT, " +
                            "table_name VARCHAR(64) NOT NULL COMMENT '表名', " +
                            "column_name VARCHAR(64) NOT NULL COMMENT '字段名', " +
                            "column_type VARCHAR(100) DEFAULT NULL COMMENT '字段类型(含长度)', " +
                            "data_type VARCHAR(50) DEFAULT NULL COMMENT '数据类型', " +
                            "is_required TINYINT DEFAULT 0 COMMENT '是否必填', " +
                            "is_unique TINYINT DEFAULT 0 COMMENT '是否唯一', " +
                            "is_visible TINYINT DEFAULT 1 COMMENT '是否在前端可见', " +
                            "dict_type VARCHAR(64) DEFAULT NULL COMMENT '字典类型', " +
                            "label VARCHAR(100) DEFAULT NULL COMMENT '显示标签', " +
                            "sort INT DEFAULT 0, " +
                            "remark VARCHAR(255) DEFAULT NULL, " +
                            "create_time DATETIME DEFAULT CURRENT_TIMESTAMP, " +
                            "update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, " +
                            "UNIQUE KEY uk_table_column (table_name, column_name), " +
                            "INDEX idx_table_name (table_name)" +
                            ") COMMENT='数据字典-字段级配置'"
            );

            log.info("Dictionary tables ensured (sys_dict_table, sys_dict_field)");
        } catch (Exception e) {
            log.warn("Init dictionary schema failed: {}", e.getMessage());
        }
    }
}


